<template>
  <q-page class="q-pa-md">
    <!-- 操作按钮 -->
    <div class="q-mb-md">
      <q-btn color="primary" icon="add" label="新增部门" @click="showAddDialog(null)" />
      <q-btn color="grey" icon="refresh" label="刷新" class="q-ml-sm" @click="loadDeptTree" />
    </div>

    <!-- 部门树表格 -->
    <q-card flat bordered>
      <q-card-section>
        <div class="text-h6">部门列表</div>
      </q-card-section>
      <q-card-section>
        <q-table
          :rows="flattenDeptData"
          :columns="columns"
          row-key="deptId"
          :loading="loading"
          :pagination="{ rowsPerPage: 0 }"
          :rows-per-page-options="[0]"
          flat
          bordered
          hide-pagination
        >
          <!-- 状态列 -->
          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-badge :color="props.row.status === '1' ? 'positive' : 'negative'">
                {{ props.row.status === '1' ? '启用' : '停用' }}
              </q-badge>
            </q-td>
          </template>

          <!-- 操作列 -->
          <template v-slot:body-cell-actions="props">
            <q-td :props="props" class="q-gutter-x-sm">
              <q-btn dense color="primary" icon="edit" @click="showEditDialog(props.row)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn dense color="positive" icon="add" @click="showAddDialog(props.row)">
                <q-tooltip>添加子部门</q-tooltip>
              </q-btn>
              <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row)">
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑部门' : '新增部门' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <q-input v-model="deptForm.parentName" label="上级部门" outlined readonly>
              <template v-slot:append>
                <q-icon name="close" class="cursor-pointer" @click="clearParent" />
              </template>
            </q-input>

            <q-input
              v-model="deptForm.deptName"
              label="部门名称"
              :rules="[(val) => !!val || '部门名称不能为空']"
              outlined
            />

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input
                  v-model="deptForm.orderNum"
                  label="显示排序"
                  type="number"
                  :rules="[(val) => val >= 0 || '排序必须大于等于0']"
                  outlined
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input v-model="deptForm.leader" label="负责人" outlined />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input v-model="deptForm.phone" label="联系电话" outlined />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input v-model="deptForm.email" label="邮箱" type="email" outlined />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="deptForm.status"
                  label="状态"
                  :options="statusOptions"
                  outlined
                  emit-value
                  map-options
                />
              </div>
            </div>

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 选择上级部门对话框 -->
    <q-dialog v-model="parentDialogVisible" persistent>
      <q-card style="width: 400px">
        <q-card-section>
          <div class="text-h6">选择上级部门</div>
        </q-card-section>
        <q-card-section>
          <q-tree
            :nodes="deptTreeForSelect"
            node-key="deptId"
            label-key="deptName"
            v-model:selected="selectedParentId"
            default-expand-all
            :no-connectors="true"
          >
            <template v-slot:default-header="prop">
              <div class="row items-center">
                <q-icon name="account_tree" class="q-mr-sm" />
                {{ prop.node.deptName }}
                <q-badge v-if="prop.node.status === '0'" color="negative" class="q-ml-sm"
                  >已停用</q-badge
                >
              </div>
            </template>
          </q-tree>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn label="取消" v-close-popup flat color="primary" />
          <q-btn label="确定" color="primary" @click="confirmParentSelect" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'deptName', label: '部门名称', field: 'deptName', align: 'left' },
  { name: 'orderNum', label: '排序', field: 'orderNum', align: 'center' },
  { name: 'leader', label: '负责人', field: 'leader', align: 'center' },
  { name: 'phone', label: '联系电话', field: 'phone', align: 'center' },
  { name: 'email', label: '邮箱', field: 'email', align: 'center' },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center' },
  { name: 'actions', label: '操作', align: 'center' },
]

// 状态选项
const statusOptions = [
  { label: '启用', value: '1' },
  { label: '停用', value: '0' },
]

// 数据状态
const deptTree = ref([])
const flattenDeptData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const parentDialogVisible = ref(false)
const isEdit = ref(false)
const deptForm = ref(initDeptForm())
const selectedParentId = ref(null)
const currentParent = ref(null)

// 初始化部门表单
function initDeptForm() {
  return {
    deptId: null,
    parentId: 0,
    parentName: '顶级部门',
    deptName: '',
    orderNum: 0,
    leader: '',
    phone: '',
    email: '',
    status: '1',
  }
}

// 处理后的部门树（用于选择上级部门）
const deptTreeForSelect = computed(() => {
  return [
    {
      deptId: 0,
      deptName: '顶级部门',
      status: '1',
      children: deptTree.value,
    },
  ]
})

// 初始化加载数据
onMounted(() => {
  loadDeptTree()
})

// 加载部门树
function loadDeptTree() {
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    deptTree.value = [
      {
        deptId: 1,
        parentId: 0,
        deptName: 'XX科技有限公司',
        orderNum: 1,
        leader: '张三',
        phone: '15888888888',
        email: 'xx@qq.com',
        status: '1',
        createTime: '2022-01-01 12:00:00',
        children: [
          {
            deptId: 2,
            parentId: 1,
            deptName: '深圳总公司',
            orderNum: 1,
            leader: '李四',
            phone: '15888888888',
            email: 'xx@qq.com',
            status: '1',
            createTime: '2022-01-01 12:00:00',
            children: [
              {
                deptId: 5,
                parentId: 2,
                deptName: '研发部门',
                orderNum: 1,
                leader: '王五',
                phone: '15888888888',
                email: 'xx@qq.com',
                status: '1',
                createTime: '2022-01-01 12:00:00',
              },
              {
                deptId: 6,
                parentId: 2,
                deptName: '测试部门',
                orderNum: 2,
                leader: '赵六',
                phone: '15888888888',
                email: 'xx@qq.com',
                status: '1',
                createTime: '2022-01-01 12:00:00',
              },
            ],
          },
          {
            deptId: 3,
            parentId: 1,
            deptName: '长沙分公司',
            orderNum: 2,
            leader: '钱七',
            phone: '15888888888',
            email: 'xx@qq.com',
            status: '1',
            createTime: '2022-01-01 12:00:00',
            children: [
              {
                deptId: 7,
                parentId: 3,
                deptName: '市场部门',
                orderNum: 1,
                leader: '孙八',
                phone: '15888888888',
                email: 'xx@qq.com',
                status: '1',
                createTime: '2022-01-01 12:00:00',
              },
              {
                deptId: 8,
                parentId: 3,
                deptName: '财务部门',
                orderNum: 2,
                leader: '周九',
                phone: '15888888888',
                email: 'xx@qq.com',
                status: '0',
                createTime: '2022-01-01 12:00:00',
              },
            ],
          },
        ],
      },
    ]

    // 扁平化部门数据用于表格展示
    flattenDeptData.value = flattenTree(deptTree.value)
    loading.value = false
  }, 500)
}

// 扁平化树形数据
function flattenTree(tree) {
  const result = []
  const flatten = (nodes, level = 0) => {
    nodes.forEach((node) => {
      result.push({
        ...node,
        level,
        hasChildren: node.children && node.children.length > 0,
      })
      if (node.children) {
        flatten(node.children, level + 1)
      }
    })
  }
  flatten(tree)
  return result
}

// 显示新增对话框
function showAddDialog(parent) {
  isEdit.value = false
  deptForm.value = initDeptForm()

  if (parent) {
    currentParent.value = parent
    deptForm.value.parentId = parent.deptId
    deptForm.value.parentName = parent.deptName
  }

  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  deptForm.value = { ...row }

  // 设置父级名称
  if (row.parentId === 0) {
    deptForm.value.parentName = '顶级部门'
  } else {
    const parent = findParent(deptTree.value, row.deptId)
    if (parent) {
      deptForm.value.parentName = parent.deptName
    }
  }

  dialogVisible.value = true
}

// 查找父节点
function findParent(nodes, deptId) {
  for (const node of nodes) {
    if (node.children) {
      const found = node.children.find((child) => child.deptId === deptId)
      if (found) return node

      const parent = findParent(node.children, deptId)
      if (parent) return parent
    }
  }
  return null
}

// 打开选择上级部门对话框
function openParentSelect() {
  parentDialogVisible.value = true
}

// 确认选择上级部门
function confirmParentSelect() {
  if (selectedParentId.value === 0) {
    deptForm.value.parentId = 0
    deptForm.value.parentName = '顶级部门'
  } else {
    const parent = findNode(deptTree.value, selectedParentId.value)
    if (parent) {
      deptForm.value.parentId = parent.deptId
      deptForm.value.parentName = parent.deptName
    }
  }
  parentDialogVisible.value = false
}

// 查找节点
function findNode(nodes, deptId) {
  for (const node of nodes) {
    if (node.deptId === deptId) return node
    if (node.children) {
      const found = findNode(node.children, deptId)
      if (found) return found
    }
  }
  return null
}

// 清空父级选择
function clearParent() {
  deptForm.value.parentId = 0
  deptForm.value.parentName = '顶级部门'
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '部门信息已更新' : '部门创建成功',
  })
  dialogVisible.value = false
  loadDeptTree()
}

// 确认删除
function confirmDelete(row) {
  if (row.hasChildren) {
    $q.notify({
      type: 'negative',
      message: '该部门包含子部门，请先删除子部门',
    })
    return
  }

  $q.dialog({
    title: '确认删除',
    message: `确定要删除部门 ${row.deptName}  吗？`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '部门已删除',
    })
    loadDeptTree()
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }

  // 缩进显示层级关系
  tbody tr {
    td:first-child {
      padding-left: calc(1rem * var(--level));
    }
  }
}

.q-tree {
  font-size: 16px;

  .q-tree__node-header {
    padding: 8px 0;
  }
}
</style>
